package edu.itesm.rm.face
{
	import com.quasimondo.bitmapdata.CameraBitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import jp.maaash.ObjectDetection.ObjectDetector;
	import jp.maaash.ObjectDetection.ObjectDetectorEvent;
	import jp.maaash.ObjectDetection.ObjectDetectorOptions;
	
	/**
	 * ...
	 * @author Aldo Reyes
	 */
	public class FacePositionDetector extends EventDispatcher
	{
		
		
		//private var view:Sprite;
		private var camera:CameraBitmap;
		private var detectionMap:BitmapData;
		private var drawMatrix:Matrix;
		//private var faceRectContainer:Sprite;
		private var detector:ObjectDetector;
		private var w:int = 160;
		private var h:int = 120;
		private var _fx:Number;
		private var _fy:Number;
		
		public function get facePercentageX():Number { return _fx; }
		
		public function get facePercentageY():Number { return _fy; }
		
		public function FacePositionDetector() 
		{
			
		}
		
		public function init():void {
			
			
			
			//view = new Sprite();
			//addChild(view);

			camera = new CameraBitmap( w, h, 15 );
			//view.addChild( new Bitmap( camera.bitmapData ) );
			detectionMap = new BitmapData( w, h, false, 0 );
			drawMatrix = new Matrix( 1, 0, 0, 1 );
			
			//faceRectContainer = new Sprite;
			//view.addChild( faceRectContainer );
			
			detector = new ObjectDetector();
			
			var options:ObjectDetectorOptions = new ObjectDetectorOptions();
			options.min_size  = 30;
			detector.options = options;
			detector.addEventListener(ObjectDetectorEvent.DETECTION_COMPLETE, detectionHandler );
			camera.addEventListener( Event.RENDER, cameraReadyHandler );
		}
		
		public function destroy():void 
		{
			detector.removeEventListener(ObjectDetectorEvent.DETECTION_COMPLETE, detectionHandler );
			camera.removeEventListener( Event.RENDER, cameraReadyHandler );
		}
		
		private function cameraReadyHandler( event:Event ):void
		{
			detectionMap.draw(camera.bitmapData, drawMatrix, null, "normal", null, true);
			detector.detect( detectionMap );
		}
		
		private function detectionHandler( e :ObjectDetectorEvent ):void
		{
			//var g :Graphics = faceRectContainer.graphics;
			//g.clear();
			if ( e.rects && e.rects.length > 0) {
				var rect:Rectangle = e.rects[0];
				_fx = 1-(rect.x+rect.width*.5) / w;
				_fy = 1-(rect.y+rect.height*.5) / h;
				dispatchEvent(new Event(Event.CHANGE));
			}
			
		}
		
	}

}